const snmp = require('net-snmp')

//const back = {success: false, data: ''}

//表=============================================================

function sortInt(a, b) {
  if (a > b)
    return 1;
  else if (b > a)
    return -1;
  else
    return 0;
}


var maxRepetitions = 20;

// The maxRepetitions argument is optional, and will be ignored unless using
// SNMP verison 2c

function getArp(session) {
  var back = {success: false, data: ''}
  session.on("error", function (error) {
    console.log("snmp会话出错", error.toString());
    session.close();
  });
  return new Promise(function (resolve, reject) {
    var oid = "1.3.6.1.2.1.4.22";//arp table
    session.table(oid, maxRepetitions, responseCb);
    var arpType = {1: 'other', 2: 'invalid', 3: 'dynamic', 4: 'static'}

    function responseCb(error, table) {
      if (error) {
        back.data = error.toString()
        resolve(back)
      } else {
        // This code is purely used to print rows out in index order,
        // ifIndex's are integers so we'll sort them numerically using
        // the sortInt() function above
        var arpTable = []
        try {
          for (index in table) {
            //console.log(table[index]['3']+"|"+table[index]['2'].toString("hex"))
            //console.log(table[index])
            arpTable.push({
              'netIndex': table[index]['1'],
              'ip': table[index]['3'],
              'mac': table[index]['2'].toString("hex"),
              'type': arpType[table[index]['4']],
              'time': new Date()
            })
          }
        } catch (e) {
          console.log(e.toString())
        }
        back.success = true
        back.data = arpTable
        resolve(back)
        // var indexes = [];
        // for (index in table)
        //     indexes.push (parseInt (index));
        // indexes.sort (sortInt);

        // // Use the sorted indexes we've calculated to walk through each
        // // row in order
        // for (var i = 0; i < indexes.length; i++) {
        //     // Like indexes we sort by column, so use the same trick here,
        //     // some rows may not have the same columns as other rows, so
        //     // we calculate this per row
        //     var columns = [];
        //     for (column in table[indexes[i]])
        //         columns.push (parseInt (column));
        //     columns.sort (sortInt);

        //     // Print index, then each column indented under the index
        //     console.log ("row for index = " + indexes[i]);
        //     for (var j = 0; j < columns.length; j++) {
        //         console.log ("   column " + columns[j] + " = "
        //                 + table[indexes[i]][columns[j]]);
        //     }
        // }
      }
    }
  })
}

//获取IP地址表
function getIpaddr(session) {
  var back = {success: false, data: ''}
  session.on("error", function (error) {
    console.log(error.toString());
    session.close();
  });
  return new Promise(function (resolve, reject) {
    var oid = "1.3.6.1.2.1.4.20";// ipaddr
    session.table(oid, maxRepetitions, responseCb);

    async function responseCb(error, table) {
      if (error) {
        back.data = error.toString()
        resolve(back)
      } else {
        var arpTable = []
        //查看一下接口表好比较出VLAN号
        var iftable = []
        await getIftable(session).then(back => {
          iftable = back.data
        })
        for (index in table) {
          //arpTable.push({'netIndex': table[index]['2'], 'ip': table[index]['1'], 'mask': table[index]['3']})
          var ifName = iftable.find(n => n.netIndex == table[index]['2']).name
          arpTable.push({'ifname': ifName, 'ip': table[index]['1'], 'mask': table[index]['3']})
        }
        back.success = true
        back.data = arpTable
        resolve(back)
      }
    }
  })

}

//获取接口信息
function getIftable(session) {
  var back = {success: false, data: ''}
  session.on("error", function (error) {
    console.log(error.toString());
    session.close();
  });
  return new Promise(function (resolve, reject) {
    var oid = "1.3.6.1.2.1.2.2";// iftable
    session.table(oid, maxRepetitions, responseCb);

    function responseCb(error, table) {
      if (error) {
        back.data = error.toString()
        resolve(back)
      } else {
        // This code is purely used to print rows out in index order,
        // ifIndex's are integers so we'll sort them numerically using
        // the sortInt() function above
        var arpTable = []
        for (index in table) {
          //console.log(table[index]['1'],table[index]['2'].toString())
          arpTable.push({'netIndex': table[index]['1'], 'name': table[index]['2'].toString()})
        }
        back.success = true
        back.data = arpTable
        resolve(back)
      }
    }
  })

}


module.exports.getArp = getArp;
module.exports.getIpaddr = getIpaddr;
module.exports.getIftable = getIftable;
module.exports.snmp = snmp;
//module.exports.getSysInfo = getSysInfo;
